package models

import (
	"encoding/json"
	"errors"
	"github.com/spf13/cast"
	"strings"
)

type AgentIncomeLog struct {
	Model
	AgentId    int     `json:"agent_id" gorm:"comment:'代理商id'"`
	Amount     float32 `json:"amount" gorm:"type:decimal(10,2);comment:'收入金额'"`
	OrderId    int     `json:"order_id" gorm:"comment:'订单id'"`
	MerchantId int     `json:"merchant_id" gorm:"comment:'商户id'"`
	Type       int     `json:"type" gorm:"comment:'1=收入 2=提现'"`
}

// AgentIncomeLogAdd 创建收入记录
func AgentIncomeLogAdd(order *MerchantOrder) error {
	var infos []map[string]any
	err := json.Unmarshal([]byte(order.PayInfo), &infos)
	if err != nil {
		return err
	}

	for i := 0; i < len(infos); i++ {
		mapd := cast.ToStringMap(infos[i])
		log := &AgentIncomeLog{
			AgentId:    cast.ToInt(mapd["agent_id"]),
			Amount:     cast.ToFloat32(mapd["rate"]) * order.Amount * 0.01,
			OrderId:    cast.ToInt(order.ID),
			MerchantId: order.MerchantId,
			Type:       1,
		}
		db.Create(log)
	}
	return nil
}

// AgentIncomeLogExist 判断是否存在，并且返回数据
func AgentIncomeLogExist(ids string) (float32, error) {
	var count int64
	if err := db.Model(&AgentIncomeLog{}).
		InnerJoins("INNER JOIN merchant_orders ON agent_income_logs.order_id = merchant_orders.id").
		Where("FIND_IN_SET(agent_income_logs.id, ?)", ids).Count(&count).Error; err != nil {
		return 0, err
	}
	if cast.ToInt(count) != strings.Count(ids, ",")+1 {
		return 0, errors.New("订单不存在")
	}

	var amount float32
	if err := db.Model(&AgentIncomeLog{}).Select("COALESCE(SUM(amount),0)").Where("FIND_IN_SET(id, ?)", ids).Scan(&amount).Error; err != nil {
		return 0, err
	}

	if err := db.Model(&AgentIncomeLog{}).Where("FIND_IN_SET(id, ?)", ids).Update("type", 2).Error; err != nil {
		return 0, err
	}

	return amount, nil
}

// GetAgentBalance 获取账户余额
func GetAgentBalance(agentId int) (string, error) {
	var balance string
	if err := db.Model(&AgentIncomeLog{}).Select("COALESCE(SUM(amount),0) AS balance").Where("agent_id = ? AND type = 1", agentId).Scan(&balance).Error; err != nil {
		return "", err
	}

	return balance, nil
}
